package ajax02.service.impl;

import ajax02.bean.User;
import ajax02.mapper.UserMapper;
import ajax02.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public List<User> selectLike(String username) {
        List<User> users = null;
        SqlSession sqlSession = null;
        InputStream is = null;
        try{

            is = Resources.getResourceAsStream("MyBatisConfig.xml");

            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

            sqlSession = sqlSessionFactory.openSession(true);

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            users = mapper.selectLike(username);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {

            if(sqlSession != null) {
                sqlSession.close();
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return users;
    }
}
